package com.miao.base.exception;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


//全局异常处理器
@Slf4j
@RestControllerAdvice//这个注解默认返回json
public class GlobalExceptionHandler {

   //对项目的自定义异常类型进行处理
   @ExceptionHandler(XueChengPlusException.class)
   @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//返回前端的http状态码
   public RestErrorResponse customException(XueChengPlusException e){

    //记录异常
    log.error("系统异常{}",e.getErrMessage(),e);

    //解析出异常信息
    String errMessage = e.getErrMessage();
       return new RestErrorResponse(errMessage);
   }

    //JSR303抛得是这种类型的异常
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse MethodArgumentNotValidexception(MethodArgumentNotValidException e){
        //解析异常
        BindingResult bindingResult = e.getBindingResult();
        //存放错误信息，一次性多个校验信息
        List<String> errors = new ArrayList<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errors.add(fieldError.getDefaultMessage());//逐个存放
        }
        //将list中的信息拼接
        String join = StringUtils.join(errors, ",");

        log.error("系统异常{}",e.getMessage(),join);

        //解析出异常信息
        return new RestErrorResponse(join);
    }


   @ResponseBody
   @ExceptionHandler(Exception.class)
   @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
   public RestErrorResponse exception(Exception e){
        if(e.getMessage().equals("不允许访问")){
            log.error("无权访问！！！");
            return new RestErrorResponse("您没有权限访问哦~~");
        }

    //记录异常
    log.error("系统异常{}",e.getMessage(),e);

    //解析出异常信息
       return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
   }


}
